<template>
  <div class="page-emr-content" :class="{ 'disabled-font': disabled }">
    <el-tabs v-model="d.tabName">
      <el-tab-pane label="emr" name="emr">
        <template v-for="(item, index) in templates">
          <EMRCell
            v-if="!(hideButton && item.model === '辅助检查')"
            :key="index"
            :docType="docType"
            :title="item.title"
            :subtitle="item.subtitle"
            :data="item.data"
            :ref="setRefs"
            :disabled="disabled"
            :class="{ domScroll1: index === 1 }"
            @change="formCahnge(['diagnostics', 'cnMedicineDiagnostics'])"
            @showTips="showTips"
          />
        </template>
        <div v-if="d.refs.length > 0 && !hideButton" class="fileClass">
          <h3>上传附件：</h3>
          <file-upload
            :disabled="disabled"
            v-model="d.files"
            ref="fileUploadRef"
          ></file-upload>
        </div>
        <diagnostic-view
          :pid="id"
          :emrAcuteId="d.emrAcuteId"
          :emrControlId="d.emrControlId"
          :emrId="emrId"
          v-if="!risk"
          :data="diagnostics"
          @updateAssessment="updateAssessment"
          @toDiagnostic="toDiagnostic(false, 'diagnostics')"
          ref="diagnosticRef"
          :disabled="disabled"
          :recordDate="recordDate"
          :attrs="attrs"
        ></diagnostic-view>
        <diagnostic-view
          v-else
          :data="riskMedicineDiagnostics"
          @toDiagnostic="toDiagnostic(true)"
          ref="riskDiagnosticRef"
          :disabled="disabled"
          :recordDate="recordDate"
        ></diagnostic-view>
        <!-- 中医相关 -->
        <template v-if="showCNEMR">
          <div
            style="display: flex; align-items: center"
            v-if="isAsthmaDocType && !risk && cnMedicineDiagnostics.length > 0"
          >
            <span style="margin-right: 20px">显示中医辅助模块</span>
            <el-switch
              v-model="cnSwitch"
              :disabled="disabled"
              @change="cnSwitchChange"
            />
          </div>
          <template v-if="cnSwitch && isAsthmaDocType">
            <EMRCell
              v-for="(item, index) in cnMedicineTemplate"
              :key="index"
              :title="item.title"
              :subtitle="item.subtitle"
              :data="item.data"
              :ref="setCNRefs"
              :disabled="disabled"
              @change="formCahnge(['cnMedicineDiagnostics'])"
            ></EMRCell>
            <diagnostic-view
              title="中医辨证"
              :data="cnMedicineDiagnostics"
              @toDiagnostic="toDiagnostic(false, 'cnMedicineDiagnostics')"
              ref="cnDiagnosticRef"
              :disabled="disabled"
              :recordDate="recordDate"
            ></diagnostic-view>
          </template>
        </template>
      </el-tab-pane>
      <el-tab-pane label="txt" name="txt">
        <emr-previewer :data="d.emrTexts"></emr-previewer>
      </el-tab-pane>
    </el-tabs>
    <AffixHubs v-if="!hideButton">
      <template v-slot:TipsHub>
        <diagnostisCvaTips
          v-if="isAsthmaDocType"
          class="footer-button"
        ></diagnostisCvaTips>
        <diagnosisDifferential
          v-if="isAsthmaDocType"
          class="footer-button"
        ></diagnosisDifferential>
        <diagnosisTips
          v-if="isAsthmaDocType"
          class="footer-button"
        ></diagnosisTips>
        <el-button
          v-if="isAsthmaDocType && !risk"
          class="footer-button"
          @click="showQrCode"
        >
          二维码
        </el-button>
      </template>
      <template v-slot:functionHub >
        <el-button
          v-if="isAsthmaDocType && !risk"
          class="footer-button"
          @click="conver"
        >
          切换
        </el-button>
        <debounceBtn
          class="footer-button"
          type="primary"
          @debounce="printClick"
          :disabled="disabled"
        >
          打印
        </debounceBtn>
        <debounceBtn
          class="footer-button"
          type="primary"
          @debounce="onSubmit(1)"
          :disabled="disabled"
        >
          {{ risk ? '保存风险筛查' : '保存' }}
        </debounceBtn>
        <debounceBtn
          class="footer-button"
          v-if="!risk"
          type="primary"
          @debounce="onSubmit(2)"
          :disabled="disabled"
        >
          提交
        </debounceBtn>
        <debounceBtn
          class="footer-button"
          v-if="!risk"
          type="primary"
          @debounce="withdraw"
          :disabled="!disabled"
        >
          撤回病历
        </debounceBtn>
      </template>
    </AffixHubs>
    <EmrTips ref="emrTipsRef"></EmrTips>
  </div>
</template>
<script>
  import {
    computed,
    reactive,
    ref,
    onMounted,
    nextTick,
    watch,
    provide,
    toRefs,
  } from 'vue'
  import common from '@/utils/common'
  import {
    emrConvert,
    diagnosis,
    withdrawEmrWithEmrId,
  } from '@/api/modules/emr'
  import { ElMessage } from 'element-plus'
  import { useStore } from 'vuex'
  import EmrTips from '@/components/EmrTips/index.vue'
  import { useRouteAndRouter } from '@/hooks/core/useRouteAndRouter.js'
  import { useEmrData } from '../../hooks/useEmrData.js'
  import diagnosisTips from './components/diagnosisTips'
  import diagnosisDifferential from './components/diagnosisDifferential'
  import diagnostisCvaTips from './components/diagnostisCvaTips'
  import AffixHubs from '@/components/AffixHubs'
  import { cloneDeep } from 'lodash-es'
  import moment from 'moment'
  import {
    emrConverTextToAttrs,
    getEmrTextToKV,
  } from '@/utils/lib/EmrTextConvert/index'
  import asthmaData from './components/asthma.js'

  import { useAsthmaBus } from './hooks/useAsthmaBus.ts'
  // import { useOnce } from '@/hooks/core/useOnce.js'
  import { diffTimesToYear } from '@/utils/timeTools'

  import { getCurrentInstance } from 'vue'
  import { onMountedOrActivated } from '@/hooks/core/onMountedOrActivated'
  import asthmaUtils from './utils.js'

  export default {
    name: 'asthma',
    props: {
      id: Number,
      vid: Number,
      emrId: [Number, String],
      docType: [Number, String],
      disabled: Boolean,
      recordDate: String,
      hideButton: {
        type: Boolean,
        default: false,
      }
    },
    emits: ['toData', 'print'],
    components: {
      EmrTips,
      diagnosisTips,
      diagnosisDifferential,
      diagnostisCvaTips,
      AffixHubs,
    },
    setup(props, context) {
      // const asthmaBus = useEventBus()
      // provide('asthmaBus', asthmaBus)
      const { busDict, addBus, updateBus, deleteBus, busAllEmit } =
        useAsthmaBus()
      watch(
        () => props.recordDate,
        (val) => {
          console.log('props.recordDate =' + val)
        }
      )
      function getRecordDateFunc() {
        return props.recordDate
      }
      provide('asthmaBusDict', busDict)
      provide('asthmaBusAddBus', addBus)
      provide('asthmaBusUpdateBus', updateBus)
      provide('asthmaBusDeleteBus', deleteBus)
      provide('busAllEmit', busAllEmit)
      provide('recordDate', getRecordDateFunc)
      // 销毁组件时 需要销毁所有的bus
      const setRefs = function (el) {
        // 这里需要数组长度判断，防止死循环 大于等于后 就不用记录了
        if (el !== null && d.refs.length <= templates.value.length)
          d.refs.push(el)
      }

      const setCNRefs = function (el) {
        if (el !== null && d.cnRefs.length <= cnMedicineTemplate.value.length) {
          d.cnRefs.push(el)
        }
      }
      // 获取模板数据
      const diagnosticRef = ref()
      const cnDiagnosticRef = ref()
      const riskDiagnosticRef = ref()
      const getData = function (isConver = false) {
        let newObj = {}
        d.refs.forEach((ref) => {
          newObj = { ...newObj, ...ref.getData() }
        })
        d.cnRefs.forEach((ref) => {
          newObj = { ...newObj, ...ref.getData() }
        })
        if (diagnosticRef.value) {
          newObj = { ...newObj, ...diagnosticRef.value.getData() }
        }
        // TODO 为什么第一次为undefine
        if (cnDiagnosticRef.value) {
          newObj = { ...newObj, ...cnDiagnosticRef.value.getData() }
        }
        if (riskDiagnosticRef.value) {
          newObj = { ...newObj, ...riskDiagnosticRef.value.getData() }
        }
        if (isConver) return newObj
        const data = []
        Object.keys(newObj).forEach((key) => {
          let item = newObj[key]
          if (key === 'attr520') {
            console.log('attr520 test1')
          }
          if (Array.isArray(item)) {
            item = item.join(',')
          }
          if (item) {
            data.push({ attrValue: item, name: key })
          }
        })
        return data
      }

      const isAsthmaDocType = computed(() => {
        return asthmaUtils.isAsthmaDocType(props.docType)
      })
      const attrs = computed(() => {
        return getData(true)
      })
      const { initEmrData, diffDiagnostic, filterFollowDate } = useEmrData()
      // 普通的病历
      const templates = ref([])
      // 普通诊断
      const diagnostics = ref([])
      // 中医的病历
      const cnMedicineTemplate = ref([])
      // 中医诊断
      const cnMedicineDiagnostics = ref([])
      // 风险筛查诊断
      const riskMedicineDiagnostics = ref([])
      // 中医是否有填写
      // const showCN = ref(false)
      // 外部注入参数
      const initEmr = async function (data) {
        // data = asthmaData.data;
        d.tabName = 'emr'
        if (!data) return
        d.refs = []
        d.cnRefs = []
        console.log('data.treatmentType', data.treatmentType)
        d.treatmentType = data.treatmentType
        // d.data = data.caseTempleReq.value
        d.files = data.files

        const { acuteWheezingActionPlanId, controlActionPlanId } =
          data.caseTempleReq
        // 急性喘息发作id
        if (acuteWheezingActionPlanId)
          store.dispatch('emr/setEmrAcuteId', {
            enumType: 3,
            id: acuteWheezingActionPlanId,
          })
        // 控制水平id
        if (controlActionPlanId)
          store.dispatch('emr/setControlId', {
            enumType: 3,
            id: controlActionPlanId,
          })

        const { emr, emrDiagnostics, cnEmr, cnDiagnostics, riskDiagnostics } =
          initEmrData(data.caseTempleReq.value, risk.value)

        templates.value = emr
        diagnostics.value = emrDiagnostics
        cnMedicineTemplate.value = cnEmr
        cnMedicineDiagnostics.value = cnDiagnostics
        riskMedicineDiagnostics.value = riskDiagnostics

        // showCN.value = checkShowCN()
        // cnSwitch.value = showCN.value
        // 风险筛查 riskUserId
        d.riskUserId = data.riskUserId
        // 重制禁止修改
        isMounted.value = false
        await nextTick()
        isMounted.value = true
      }

      const fileUploadRef = ref(null)
      // const imgUplodRef = ref()
      // 保存/提交
      const onSubmit = function (status) {
        let imgUplodRef = null
        d.refs.forEach((item) => {
          const imgRef = item.getImageRef()
          if (imgRef && item.title === '辅助检查') {
            imgUplodRef = imgRef
          }
        })

        //  鼻炎病历的辅助检查的没有图片上传，不需判断
        if (asthmaUtils.isAsthmaDocType(props.docType)) {
          const imgStatus = imgUplodRef.getStatus()
          // 先处理文件未上传情况
          const fileStatus = fileUploadRef.value.getStatus()
          if (fileStatus === false || imgStatus === false) {
            ElMessage.warning('还有文件在上传')
            return
          }
        }

        const riskScreeningType = risk.value ? 1 : 0
        const attrs = getData()
        const tmp = {
          attrs,
          status,
          files: d.files,
          riskScreeningType,
          ...getEmrTextToKV(attrs, d.treatmentType, getAgeType()),
        }
        const followDate = filterFollowDate(attrs)
        tmp['followDate'] = followDate ? followDate : ''
        if (riskScreeningType === 0 && d.riskUserId)
          tmp['riskUserId'] = d.riskUserId
        context.emit('toData', tmp)
      }

      function getAgeType() {
        const birthday = store.getters.patientInfo.birthday
        const recordBirthday = store.getters.emrRecordBirthday
        const ageType =
          diffTimesToYear(props.recordDate, recordBirthday || birthday) >= 6
            ? 'greaterEqual'
            : 'lessThan'

        return ageType
      }
      // 文本转换
      const conver = async function () {
        if (d.tabName === 'emr') {
          const attrs = getData()
          d.emrTexts = emrConverTextToAttrs(
            attrs,
            d.treatmentType,
            getAgeType()
          )
          console.log(d.emrTexts)
          d.tabName = 'txt'
        } else {
          d.tabName = 'emr'
        }
      }
      const store = useStore()
      const showQrCode = async function () {
        const attrs = getData()
        const res = emrConverTextToAttrs(attrs, d.treatmentType, getAgeType())
        const tmp = res
          .map((item) => {
            return { name: item.model, text: [item.text] }
          })
          .filter((item) => item.name !== '辅助检查图片')
        store.dispatch('qrcode/setQRCodeShowData', {
          config: { showTextbar: true },
          data: tmp,
        })
      }
      const toSave = function () {}
      // 提交诊断
      const toDiagnostic = async function (risk = false, type = null) {
        const attrs = getData()
        const params = {
          docType: props.docType,
          patientId: props.id,
          attrs,
          treatmentType: d.treatmentType,
          risk,
          medicalRecordId: props.emrId,
          recordDate: moment(props.recordDate).format('YYYY-MM-DD HH:mm:ss'),
        }
        const res = await diagnosis(params)

        // 重置界面
        const { emrDiagnostics, cnDiagnostics, riskDiagnostics } = initEmrData(
          res.data,
          risk
        )
        console.log('emrDiagnostics =' + JSON.stringify(emrDiagnostics))
        if (type !== 'cnMedicineDiagnostics') diagnostics.value = emrDiagnostics
        if (type !== 'diagnostics') cnMedicineDiagnostics.value = cnDiagnostics
        riskMedicineDiagnostics.value = riskDiagnostics
        // 暂时好像没有用上
        d.diagnostics = res.data

        const { controlActionPlanId, acuteWheezingActionPlanId } =
          emrDiagnostics[0]
        // 急性喘息发作id
        if (acuteWheezingActionPlanId)
          store.dispatch('emr/setEmrAcuteId', {
            enumType: 2,
            id: acuteWheezingActionPlanId,
          })
        // 控制水平id
        if (controlActionPlanId)
          store.dispatch('emr/setControlId', {
            enumType: 2,
            id: controlActionPlanId,
          })
      }
      const updateAssessment = async function (risk = false) {
        console.log('updateAssessment')
        const attrs = getData()
        const params = {
          docType: props.docType,
          patientId: props.id,
          attrs,
          treatmentType: d.treatmentType,
          risk,
          medicalRecordId: props.emrId,
          recordDate: moment(props.recordDate).format('YYYY-MM-DD HH:mm:ss'),
        }
        const res = await diagnosis(params)
        // 查询诊断里的值
        const { emrDiagnostics } = initEmrData(res.data)
        const handDiagnostic = diagnosticRef.value.getData()
        diagnostics.value[0].data = diffDiagnostic(
          cloneDeep(diagnostics.value),
          emrDiagnostics,
          handDiagnostic,
          getAgeType()
          // store.getters.patientInfo.ageType
        )
      }
      const isMounted = ref(false)
      onMounted(async () => {
        await nextTick()
        isMounted.value = true
      })
      const formCahnge = async function (resets = []) {
        if (isMounted.value) {
          // 渲染完成才能调用该方法2
          await nextTick()
          store.dispatch('emr/setEditingStatus', true)
          if (diagnosticRef.value && resets.includes('diagnostics'))
            diagnosticRef.value.reset()
          if (cnDiagnosticRef.value && resets.includes('cnMedicineDiagnostics'))
            cnDiagnosticRef.value.reset()
          if (riskDiagnosticRef.value) riskDiagnosticRef.value.reset()
        }
      }

      const cnSwitchChange = async function (val) {
        if (val === false) {
          cnDiagnosticRef.value.reset()
          d.cnRefs = []
        }
      }

      const affixChange = function (fiexStatus) {
        // 固钉修改颜色
        console.log('fiexStatus =' + fiexStatus)
      }
      const emrTipsRef = ref(null)
      const showTips = function (title) {
        emrTipsRef.value.initTitle(true, title)
      }
      const d = reactive({
        data: [],
        diagnostics: null,
        refs: [],
        cnRefs: [],
        tabName: 'emr',
        emrTexts: null,
        files: null,
        treatmentType: null,
        riskUserId: null,
        emrAcuteId: null,
        emrControlId: null,
      })

      // 风险筛查
      const { isRiskRx } = useRouteAndRouter()
      const risk = isRiskRx

      const showCN = computed(() => {
        if (showCN.value || cnSwitch.value) return true
        let isHas = false
        if (cnMedicineTemplate.value && cnMedicineTemplate.value.length > 0) {
          isHas = cnMedicineTemplate.value[0].data.some((item) => {
            if (item.b && item.b.ip) {
              if (item.b.children) {
                const isChildren = item.b.children.some((item) => {
                  if (item.b && item.b.ip) return true
                  return false
                })
                return isChildren
              }
              return true
            }
            return false
          })
        }
        let isDiagnostics = false
        if (
          cnMedicineDiagnostics.value &&
          cnMedicineDiagnostics.value.length > 0
        ) {
          isDiagnostics = cnMedicineDiagnostics.value[0].data.some((item) => {
            if (item.b && item.b.ip) {
              if (item.b.children) {
                const isChildren = item.b.children.some((item) => {
                  if (item.b && item.b.ip) return true
                  return false
                })
                return isChildren
              }
              return true
            }
            return false
          })
        }
        return isHas || isDiagnostics
      })

      const cnSwitch = ref(false)
      watch(
        showCN,
        (val) => {
          console.log('val =' + val)
          cnSwitch.value = showCN.value
          if (cnSwitch.value === false) {
            d.cnRefs = []
            // cnDiagnosticRef.value = []
          }
        },
        { immediate: true, deep: true }
      )

      const backtop = function () {
        console.log('backtop')
      }

      async function withdraw() {
        await common.syncAlert('确定撤回已提交的病历？病历修改需谨慎操作？')
        common.XmLoading(true)
        withdrawEmrWithEmrId({ medicalRecordId: props.emrId })
          .then(() => {
            common.XmLoading(false)
            common.XmMessage(0, '撤回成功！')
            store.dispatch('patient/loadPatientInfo', props.id)
            // Todo 刷新页面
            location.reload()
          })
          .catch(() => {
            common.XmLoading(false)
          })
      }
      const showCNEMR = computed(() => {
        console.log('store.getters.showCNEMR =' + store.getters.showCNEMR)
        return store.getters.showCNEMR
      })
      // 打印按钮
      function printClick() {
        context.emit('print');
      }
      return {
        withdraw,
        d,
        templates,
        diagnostics,
        setRefs,
        onSubmit,
        conver,
        toSave,
        initEmr,
        toDiagnostic,
        fileUploadRef,
        diagnosticRef,
        formCahnge,
        showQrCode,
        cnMedicineTemplate,
        cnMedicineDiagnostics,
        showTips,
        emrTipsRef,
        risk,
        showCN,
        cnSwitch,
        setCNRefs,
        affixChange,
        riskMedicineDiagnostics,
        riskDiagnosticRef,
        cnDiagnosticRef,
        backtop,
        updateAssessment,
        showCNEMR,
        attrs,
        cnSwitchChange,
        isAsthmaDocType,
        printClick,
      }
    },
  }
</script>
<style lang="scss" scoped>
  @import '@/styles/emr.scss';

  .page-emr-content {
    padding: 0;
    font-size: 18px !important;
    .content-wrapper {
      padding: 0 !important;
    }

    :deep(.el-tabs__nav-scroll) {
      height: 0px;
    }

    .fileClass {
      font-size: 18px !important;
      line-height: 18px;
      padding: 12px;
      margin: 0 0 12px 0;

      h3 {
        // margin: 0;
        margin-bottom: 12px;
        line-height: 2;
        font-size: 20px;
        margin-right: 12px;
      }
    }

    .footer {
      margin-left: 5px;
      display: flex;
      justify-content: flex-end;
    }

    // .footer-div {
    //   height: 75px;
    //   .el-button {
    //     float: right;
    //     margin-right: 12px;
    //     margin-left: 0px;
    //   }
    // }
    .hiddenView {
      height: 0px;
      overflow: hidden;
    }
  }

  .domScroll1 {
  }
</style>
